import React, {Component} from 'react';
import {
  StyleSheet,
  View,
  TextInput,
  Image,
  TouchableHighlight,
  Platform,
  Dimensions
} from 'react-native';
import Label from '../label';
import PropTypes from 'prop-types';
import Color from '../../config/theme/standard/color';
import Font from '../../config/theme/standard/fonts';
import TextField from '../textField';

const types = ['信用卡卡号', '借记卡卡号', '国内手机号', '固定电话', '普通数字'];
export default class Number extends Component {
  constructor(props) {
    super(props);
    this.state = {
      prevPropsInput: props.defaultValue ? props.defaultValue : '',
      input: props.defaultValue ? props.defaultValue : '',
      showErrorInfo: this.props.showErrorInfo,
      info: this.props.info,
      showClear: false
    };
  }

  _chooseRule() {
    let {inputType, leftText, maxLength} = this.props;
    let type = inputType ? inputType : 'number';
    let obj = {
      leftText: types[4],
      maxLength: 0,
      ruleArr: []
    };
    if (type) {
      if (type == 'creditCard') {
        obj.leftText = types[0];
        obj.ruleArr = [4, 8, 12];
        obj.maxLength = 27;
      } else if (type == 'debitCard') {
        obj.leftText = types[1];
        obj.ruleArr = [4, 8, 12, 16];
        obj.maxLength = 23;
      } else if (type == 'mobilePhone') {
        obj.leftText = types[2];
        obj.ruleArr = [3, 7];
        obj.maxLength = 13;
      } else if (type == 'telePhone') {
        obj.leftText = types[3];
        obj.ruleArr = [3, 7];
        obj.maxLength = 14;
      } else {
        obj.ruleArr = [];
        obj.maxLength = 100;
      }
    }

    obj.leftText = leftText ? leftText : obj.leftText;
    obj.maxLength = maxLength ? maxLength + obj.ruleArr.length : obj.maxLength;
    return obj;
  }

  _changeRule(text) {
    let obj = this._chooseRule();
    let ruleArr = obj.ruleArr;
    if (this.props.inputType == 'telePhone') {
      if (text[1] >= 3) {
        ruleArr = [4, 8];
      }
    }
    let ruleIndex = 0;
    let newText = '';
    if (text) {
      text = text.replace(/\s+/g,"");   //textField组件修改编码格式,原先逻辑无法精准去除空格
      for (let i = 0; i < text.length; i++) {
        if (i % ruleArr[ruleIndex] == 0 && i != 0) {
          ruleIndex++;
          newText += ' ' + text[i];
        } else {
          newText += text[i];
        }
      }
    }
    return newText;
  }

  _onBlur() {
    this.setState({
      showClear: false
    });
    if (typeof this.props.onBlur == 'function') {
      this.props.onBlur(this.state.input);
    }
  }

  _onFocus() {
    this.setState({showClear: true});
    if (typeof this.props.onFocus == 'function') {
      this.props.onFocus();
    }

  }

  _onEndEditing() {
    if (typeof(this.props.onEndEditing) === 'function') {
      this.props.onEndEditing(this.state.input);
    }
  }

  _iconFunc() {
    if (typeof this.props.rightFunc == 'function') {
      this.props.rightFunc();
    }
  }

  _iconFunc2() {
    if (typeof this.props.rightFunc2 == 'function') {
      this.props.rightFunc2();
    }
  }


  _onChangeText(text) {
    let tmpInput = this._changeRule(text);
    this.setState({input: tmpInput});
    if (this.props.onChangeText) {
      this.props.onChangeText(text);
    }
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    let infoFlag = false;
    let valueFlag = false;
    if ('showErrorInfo' in nextProps && 'info' in nextProps ) {
        infoFlag = true;
    }
    if (('defaultValue' in nextProps) && (nextProps.defaultValue !== prevState.prevPropsInput)) {
        valueFlag = true;
    }

    if(infoFlag && valueFlag){
        return {
            showErrorInfo:nextProps.showErrorInfo,
            info:nextProps.info,
            prevPropsInput: nextProps.defaultValue,
            input: nextProps.defaultValue
        };
    }else{
        if(infoFlag){
            return {
                showErrorInfo:nextProps.showErrorInfo,
                info:nextProps.info
            };
        }else if(valueFlag){
            return {
                prevPropsInput: nextProps.defaultValue,
                input: nextProps.defaultValue,
            };
        }
    }
    return null;
}

  render() {
    let {
      showClearIcon, rightIcon, rightIconStyles, showErrorInfo, errorInfoStyles, returnInfoStyles,
      type, containerStyles, labelStyles, label, placeHolder, keyboardType,
      rightText, rightTextStyles, editable, isLimitTitleWidth, isRequired, titleWidth,numberOfLines,isMerge,hasTopBorder, inputTextStyle,
    } = this.props;
    let {info, input} = this.state;
    let obj = this._chooseRule();
    const container1Styles = [styles.container1];
    const container2Styles = [styles.container2];
    container1Styles.push({ width: Dimensions.get('window').width});
    container2Styles.push({ width: Dimensions.get('window').width})
    let width = Dimensions.get('window').width;
    let keyboardTypeString = '';
    if(keyboardType == '0'){
        keyboardTypeString = 'phone-pad';
    }else if(keyboardType == '2'){
        keyboardTypeString = 'default';
    }else{
      if(Platform.OS === 'web'){
        keyboardTypeString = 'phone-pad';
      }else{
        keyboardTypeString = 'numeric';
      }
    }

    const closeCon = [styles.closeCon, Platform.OS == 'harmony' &&{ zIndex:1 }];
    const inputTxt2 = [styles.inputTxt2];
    const inputCon2 = [styles.inputCon2];
    inputCon2.push({width: Dimensions.get('window').width})
    inputTxt2.push({width: Dimensions.get('window').width - 44})
    if (rightText) {
            closeCon.push({right: 80});
            inputTxt2.push({width: width - 128})
        } else if (rightIcon) {
            closeCon.push({right: 60});
            inputTxt2.push({width: width - 114})
        } else if (!rightText && showClearIcon) {
            closeCon.push({right: 8});
            inputTxt2.push({width: width - 60})
        } else if (!rightIcon && showClearIcon) {
            closeCon.push({right: 8});
            inputTxt2.push({width: width - 60})
        }

        if(label) {
            inputCon2.push({marginTop: 4});
        }

    if(!editable && this.state.input.length != 0){
      inputTxt2.push({textAlign:'left',color:Color.number.disable});
    }

    let rightIconItem = null;
    let clearIconItem = null;
    if (showClearIcon && this.state.showClear && this.state.input.length != 0) {
      clearIconItem = (
          <View style={closeCon}>
            <TouchableHighlight 
            activeOpacity={0.7}
            underlayColor='transparent'
            onPress={() => this._onChangeText('')}
            >
              <Image source={require('../../assets/icon_number_clear.png')}
                     style={styles.closeImg}/>
            </TouchableHighlight>
          </View>
      );
    }
    if (rightIcon) {
      rightIconItem = (
          <View style={styles.iconCon}>
            <TouchableHighlight underlayColor='transparent' onPress={() => this._iconFunc()}>
              <Image style={[styles.icon, rightIconStyles]} source={rightIcon[0]}/>
            </TouchableHighlight>
          </View>
      );
    } else if (rightText) {
      rightIconItem = (
          <View style={styles.textCon}>
            <TouchableHighlight underlayColor='transparent' onPress={() => this._iconFunc()}>
              <Label text={rightText} labelStyle={[styles.rightText, rightTextStyles]}/>
            </TouchableHighlight>
          </View>
      );
    }


    let returnInfo;
    if (showErrorInfo && info) {
      returnInfo = (
          <Label text={info} labelStyle={[styles.errorInfo, errorInfoStyles]}/>
      );
    } else {
      returnInfo = (
          <Label text={info} labelStyle={[styles.info, returnInfoStyles]}/>
      );
    }

    if (this.state.showErrorInfo && info) {
      container1Styles.push({minHeight: 67});
    }

    if(this.state.input.length != 0 && placeHolder) {
        inputTxt2.push({fontWeight: '600'})
    } else {
        inputTxt2.push({fontWeight: '400'})
    }
    let content;
    if (type && type == 2) {
      content = (
          <View style={[container2Styles,{borderTopWidth: hasTopBorder ? 1 : 0}, containerStyles]}>
             {label ? <Label text={label} labelStyle={[styles.label, labelStyles]}/> : null}
            <View style={inputCon2}>
              <TextInput
                  ref='textInputRefer'
                  style={[inputTxt2, inputTextStyle]}
                  onChangeText={(text) => this._onChangeText(text)}
                  placeholder={placeHolder}
                  placeholderTextColor={Color.input.placeholder}
                  value={input}
                  editable={editable}
                  maxLength={obj.maxLength}
                  keyboardType={keyboardTypeString}
                  underlineColorAndroid={"transparent"}
                  onEndEditing={() => this._onEndEditing()}
                  onBlur={() => this._onBlur()}
                  onFocus={() => this._onFocus()}
                  numberOfLines={numberOfLines}
              />
              {clearIconItem}
              {rightIconItem}
            </View>
            <View style={styles.infoContainer}>{returnInfo}</View>
            <View style={[styles.line, {marginLeft: isMerge ? 15 : 0}]}/>
          </View>
      );
    } else {
      content = (
          <View style={[container1Styles, containerStyles]}>
            <View style={{flexDirection: 'row'}}>
              <TextField
                  title={obj.leftText}
                  isRequired={isRequired}
                  onChangeText={(text) => this._onChangeText(text)}
                  placeholder={placeHolder}
                  placeholderTextColor={Color.input.placeholder}
                  defaultValue={input}
                  editable={editable}
                  maxLength={obj.maxLength}
                  keyboardType={keyboardTypeString}
                  onBlur={() => this._onBlur()}
                  onFocus={() => this._onFocus()}
                  onEndEditing={() => this._onEndEditing()}
                  showClearIcon={showClearIcon}
                  showErrorInfo={this.state.showErrorInfo}
                  errorInfo={info}
                  rightImg={rightIcon}
                  rightFunc={() => this._iconFunc()}
                  rightFunc2={() => this._iconFunc2()}
                  isLimitTitleWidth={isLimitTitleWidth}
                  titleWidth={titleWidth}
                  numberOfLines={numberOfLines}
                  errorInfoStyles={errorInfoStyles}
                  isMerge={isMerge}
                  titleIconFunc={this.props.titleIconFunc}
                  titleIcon={this.props.titleIcon}
                  hasTopBorder={this.props.hasTopBorder}
              />
            </View>
          </View>
      );
    }

    return (
        <View>{content}</View>

    );
  }

}

Number.propTypes = {
  //样式类型
  type: PropTypes.number,
  //数值输入框类型
  inputType: PropTypes.string,
  //默认显示值
  placeHolder: PropTypes.string,
  //弹起键盘类型 0-无小数点数字键盘（默认）1-带小数点数字键盘
  keyboardType: PropTypes.number,
  //是否显示清除按钮
  showClearIcon: PropTypes.bool,
  //是否可以编辑
  editable: PropTypes.bool,
  //最大长度
  maxLength: PropTypes.number,
  //右侧Icon
  rightIcon: PropTypes.array,
  //右侧操作
  rightFunc: PropTypes.func,
  //右侧第二个图标的点击事件
  rightFunc2: PropTypes.func,
  //右侧Icon样式
  rightIconStyles: PropTypes.oneOfType([PropTypes.array, PropTypes.object, PropTypes.number]),
  //失去光标是触发的方法
  onBlur: PropTypes.func,
  //聚焦时触发的方法
  onFocus: PropTypes.func,
  //输入结束时触发的方法
  onEndEditing: PropTypes.func,
  //输入时触发的方法
  onChangeText: PropTypes.func,
  //默认值
  defaultValue: PropTypes.string,
  //错误信息
  showErrorInfo: PropTypes.bool,
  //错误信息样式
  errorInfoStyles: PropTypes.oneOfType([PropTypes.array, PropTypes.object, PropTypes.number]),
  //外部容器样式
  containerStyles: PropTypes.oneOfType([PropTypes.array, PropTypes.object, PropTypes.number]),

  //样式1左侧文本
  leftText: PropTypes.string,
  //样式2输入标签
  label: PropTypes.string,
  //样式2输入标签样式
  labelStyles: PropTypes.array,
  //样式2返显信息样式
  returnInfoStyles: PropTypes.oneOfType([PropTypes.array, PropTypes.object, PropTypes.number]),
  //提示语
  info: PropTypes.string,
  //样式2右侧文本
  rightText: PropTypes.string,
  //样式2右侧文本样式
  rightTextStyles: PropTypes.oneOfType([PropTypes.array, PropTypes.object, PropTypes.number]),
  //是否限制标题长度
  isLimitTitleWidth: PropTypes.bool,
  //是否为必输项（显示红色*号）目前只对样式一生效
  isRequired: PropTypes.bool,
  //title区域宽度
  titleWidth: PropTypes.number,
    //设置左侧标题显示行数
    numberOfLines:PropTypes.number,
    //是否跨行合并
  isMerge: PropTypes.bool,
  titleIcon:PropTypes.any,
  titleIconFunc:PropTypes.func,
  //是否有上分割线(新增)
  hasTopBorder: PropTypes.bool,
  //Type=2时，输入域样式(新增)
  inputTextStyle: PropTypes.any,
};

Number.defaultProps = {
  type: 1,
  inputType: 'number',
  placeHolder: '请输入...',
  showClearIcon: false,
  keyboardType: 0,
  showErrorInfo: false,
  info: '',
  editable: true,
  isLimitTitleWidth: true,
  isRequired: false,
  numberOfLines:1,
  isMerge: false,
 //是否有上分割线(新增)
   hasTopBorder: true,
};

const styles = StyleSheet.create({
  container1: {
    margin: 0,
    padding: 0,
    flexDirection: 'column',
    minHeight: 44,
    borderColor: Color.border,
    justifyContent: 'flex-start'
  },
  container2: {
    margin: 0,
    padding: 0,
    flexDirection: 'column',
    minHeight: 74,
    borderColor: Color.border,
    justifyContent: 'flex-start'
  },
  label: {
    paddingTop: 10,
    paddingLeft: 15,
    color: Color.number.label,
    fontSize: Font.number.labelFontSize,
  },
  inputCon: {
    width: Dimensions.get('window').width - 160,
  },
  inputCon2: {
    paddingLeft: 15,
    paddingRight: 15,
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 16
  },
  inputTxt: {
    padding: 0,
    height: 20,
    color: Color.input.normal,
    fontSize: Font.formFontSize,
  },
  inputTxt2: {
    padding: 0,
    color: Color.number.inputText,
    fontSize: Font.number.placeholderFontSize,
  },
  closeCon: {
    position: 'absolute',
    right: 16,
    top: 3
  },
  iconCon: {
    width: 50,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  textCon: {
    flexDirection: 'row',
    width: 65,
    justifyContent: 'flex-end',
    alignItems: 'center',

  },
  rightText: {
    textAlign: 'right',
    fontSize: Font.number.rightTextFontSize,
    color: Color.number.optionText
  },
  closeImg: {
    width: 28,
    height: 28,
    zIndex: 10,
    resizeMode: 'contain'
  },
  icon: {
    width: 28,
    height: 28,
    resizeMode: 'contain'
  },
  info: {
    color: Color.number.info,
    fontSize: Font.number.infoFontSize,
  },
  errorInfo: {
    color: Color.number.errorInfo,
    fontSize: Font.number.infoFontSize
  },
  line: {
    borderColor: Color.border,
    borderTopWidth: 1,
    marginTop: 11,
    marginLeft: 0,
    marginRight: 0
  },
  infoContainer: {
    paddingLeft:15,
    height: 20,
    justifyContent: 'center'
  }
});
